import { create } from 'zustand';
import { persist } from 'zustand/middleware';

interface UserState {
  user: {
    id: string | null;
    username: string | null;
    token: string | null;
  };
  isLoggedIn: boolean;
  setUser: (user: { id: string; username: string; token: string }) => void;
  logout: () => void;
}

const useUserStore = create<UserState>()(
  persist(
    (set) => ({
      user: {
        id: null,
        username: null,
        token: null,
      },
      isLoggedIn: false,
      setUser: (user) =>
        set({
          user,
          isLoggedIn: true,
        }),
      logout: () =>
        set({
          user: {
            id: null,
            username: null,
            token: null,
          },
          isLoggedIn: false,
        }),
    }),
    {
      name: 'user-storage', // 本地存储的键名
    }
  )
);

export default useUserStore;